package dd.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JTextField;

import xml.Message;
import dd.model.Event;
import dd.model.Model;
import dd.view.CreateForm;
import dd.view.ModeratorAddChoices;

/**
 * for the create event screen call after the moderator have input all the attribute and click create button get all the
 * information input and send it to server waiting for response
 */
public class RequestCreateEventController implements ActionListener {

	// attrs
	CreateForm form;
	Event event;

	// conts
	public RequestCreateEventController(CreateForm cf, Event event) {
		this.event = event;
		form = cf;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// get all information necessary for request.
		Model model = Model.getInstance();
		JComboBox mc = form.getModeComboBox();
		String mode = (String) mc.getSelectedItem();
		this.event.setMode(mode);
		System.out.println("The mode is " + event.getMode());

		JComboBox tc = form.getTypeComboBox();
		String type = (String) tc.getSelectedItem();
		this.event.setType(type);
		System.out.println("The type is " + event.getType());

		JTextField tf = form.getEventNameTextField();
		String eventName = tf.getText();
		this.event.setEventName(eventName);
		System.out.println("event name revised in requestbutton is " + eventName);
		System.out.println("event name revised in Event is " + event.getEventName());

		JTextField Mtf = form.getMTextField();
		this.event.setNumberLines(Integer.parseInt(Mtf.getText()));
		System.out.println("Maximum of lines is " + event.getNumberLines() + "");

		JTextField Ntf = form.getNTextField();
		this.event.setNumberEdges(Integer.parseInt(Ntf.getText()));
		this.event.setLeftEdges();
		System.out.println("Maximum of edges is " + event.getNumberEdges() + "");
		// create XML request to send
		// make sure to look at ClientServerEBC
		if ((Integer.parseInt(Ntf.getText()) > 0) && (Integer.parseInt(Mtf.getText()) > 0)) {
			if (event.getMode().equals("open")) {
				// if open mode, send createRequest
				String xmlString = Message.requestHeader() + "<createRequest behavior='" + event.getType() + "' type='"
						+ event.getMode() + "' question='" + event.getEventName() + "' numChoices='"
						+ event.getNumberLines() + "' numRounds='" + event.getNumberEdges() + "'>" + "<user name='"
						+ event.getUserName() + "' password='" + event.getPassword() + "'/>" + "</createRequest>"
						+ "</request>";
				Message m = new Message(xmlString);
				model.getServerAccess().sendRequest(m);
				model.setCreateForm(form);
			} else { // if closed mode, go to moderatorAddChoices screen
				ModeratorAddChoices mac = new ModeratorAddChoices(event);
				mac.setVisible(true);
				form.dispose();
			}
		} else {
			System.out.println("Please enter reasonable M and N!");
		}

	}

}
